import service from '@/services/user';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { useState } from 'react';
import UserEditDrawer from './UserEditDrawer';
import UserViewDrawer from './UserViewDrawer';

const columns: ProColumns<API.UserInfo>[] = [
  {
    title: '名字',
    dataIndex: 'name',
    copyable: false,
    ellipsis: true,
    tooltip: '名字',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '此项为必填项',
        },
      ],
    },
  },
];

export default () => {
  const { UserController } = service;
  const { data } = useModel('user');
  const { list } = data;
  const [openEditDrawer, setOpenEditDrawer] = useState(false);
  const [openViewDrawer, setOpenViewDrawer] = useState(false);
  const [currentUser, setCurrentUser] = useState<API.UserDetailInfo>({});

  const queryUserDetail = async (
    param: { userId: number },
    options: { [key: string]: any },
  ) => {
    const userDetail = await UserController.getUserDetail(param, options);
    return userDetail;
  };

  const actionColumn: ProColumns<API.UserInfo> = {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (text, record) => [
      <a
        key="editable"
        onClick={async () => {
          const user = await queryUserDetail(
            {
              userId: parseInt(record.id ?? '-1'),
            },
            {},
          );
          setCurrentUser(user);
          setOpenEditDrawer(true);
        }}
      >
        编辑
      </a>,
      <a
        key="view"
        onClick={async () => {
          const user = await queryUserDetail(
            {
              userId: parseInt(record.id ?? '-1'),
            },
            {},
          );
          setCurrentUser(user);
          setOpenViewDrawer(true);
        }}
      >
        查看
      </a>,
    ],
  };

  return (
    <>
      <ProTable<API.UserInfo>
        columns={[...columns, actionColumn]}
        cardBordered
        dataSource={list}
        editable={{
          type: 'multiple',
        }}
        rowKey="id"
        search={false}
        options={{
          setting: {
            listsHeight: 400,
          },
          reload: false,
        }}
        pagination={{
          pageSize: 5,
          onChange: (page) => console.log(page),
        }}
        dateFormatter="string"
        headerTitle="高级表格"
      />

      {/* 编辑抽屉 */}
      <UserEditDrawer
        open={openEditDrawer}
        data={currentUser}
        onClose={() => setOpenEditDrawer(false)}
      />

      {/* 查看抽屉 */}
      <UserViewDrawer
        open={openViewDrawer}
        data={currentUser}
        onClose={() => setOpenViewDrawer(false)}
      />
    </>
  );
};
